<?php
// 1908080121李定邦、1902030115李龙烽
namespace app\admin\controller;
use app\BaseController;
use think\App;

class SectionRec extends BaseController
{
    private $_section;

    public function __construct(App $app) {
        parent::__construct($app);
        $this->checkIsAdminLogin();
        $this->_section = app('db')->name('section');
    }

    /**
     * 板块列表
     * @return mixed
     */
    public function index() {
        $keyword = $this->request->get('keyword');
        $query   = $this->_section->where("s_name", "LIKE", "%$keyword%")->where("is_del", 1);
        $data    = $query->paginate(10);
        $page    = $data->render();
        $data = [
            'list'     => $data,
            'page'     => $page,
        ];

        return app('view')->fetch('', $data);
    }

    /**
     * 添加
     * @return void
     */
    public function add() {
        if ($this->request->isPost()) {
            $s_name   = $this->request->post('s_name', '', 'trim');
            $s_remark = $this->request->post('s_remark', '', 'trim');
            $data = [
                's_name'   => $s_name,
                's_remark' => $s_remark,
                'is_del'   => 1,
            ];
            try {
                $file   = $this->request->file('s_img2');
                if ($file) {
                    $s_img = app('filesystem')->disk('portrait')->putFile('section', $file, 'md5');
                    $data['s_img'] = $s_img;
                }
            } catch (\Exception $exception) {

            }
            $res = app('db')->name('section')->insert($data);
            $res ? $this->success('添加成功', '/sec/rec') : $this->error('添加失败');
        } else {
            return app('view')->fetch('');
        }
    }

    /**
     *
     * @return \think\response\Json
     */
    public function delete() {
        $sid = $this->request->get('sid');
        $sid = is_array($sid) ? $sid : [$sid];
        $res = $this->_section->whereIn('s_id', $sid)->delete();
        $data = [
            'rs' => true,
            'msg' => $res ? '彻底删除成功' : '未知错误'
        ];

        return json($data);
    }

    /**
     * 恢复板块
     * @return \think\response\Json
     */
    public function normal() {
        $sid = $this->request->get('sid');
        $sid = is_array($sid) ? $sid : [$sid];
        $res = $this->_section->whereIn('s_id', $sid)->update(['is_del' => 0]);
        $data = [
            'rs' => true,
            'msg' => $res ? '恢复成功' : '未知错误'
        ];

        return json($data);
    }

}